﻿using AutoMapper;
using MediatR;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Internal;
using Tb.App.API.Applications.Command.Basic;
using Tb.App.Domain.Rabbit.Basic;
using Tb.App.ErrorCode;
using Tb.App.Infrastructure.Interfaces;

namespace Tb.App.API.Applications.CommandHandler.Basic
{
    /// <summary>
    /// 添加溯源商品基本信息 命令
    /// </summary>
    public class AddBasicCommandHandler : IRequestHandler<AddBasicCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<BasicModel> basicRep;
        private readonly IMapper mapper;

        public AddBasicCommandHandler(IBaseRepository<BasicModel> basicRep,IMapper mapper)
        {
            this.basicRep = basicRep;
            this.mapper = mapper;
        }
        public async Task<ApiResult<int>> Handle(AddBasicCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> result = new ApiResult<int>();
            //生产批次唯一
            var count=await basicRep.GetAll().CountAsync(x=>!x.IsDel&&x.Batch==request.Batch);
            if (count > 0) 
            {
                return new ApiResult<int>
                {
                    Code=ApiEnum.添加失败,
                    Message="生产批次重复了!!!!",
                    Data=-1
                };
            }
            //添加未完成 有待修改!!!!

            var entity=mapper.Map<BasicModel>(request);
            entity.Creator=request.Creator;
            entity.CreatorDate =DateTime.Now;
            var res= await basicRep.AddAsync(entity);
            if(res>0)
            {
                result.Code = ApiEnum.添加成功;
                result.Message = "添加成功";
                result.Data = res;
            }
            else
            {
                result.Code = ApiEnum.添加失败;
                result.Message = "添加失败";
                result.Data = res;
            }

                return await Task.FromResult(result);
        }
    }
}
